﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp5
{
    class 委托事件
    {
        int ClickNum = 0;
        MyEventByDelegate myEventByDelegate = new MyEventByDelegate();
        public 委托事件()
        {
            // delegate如果在多个函数指向它，一个设为null则其他的也受影响，所以要用+=
            // 当然因为这个问题可以直接使用event触发事件
            myEventByDelegate.ShowEvent += new MyEventByDelegate.Show(MyShow);
            myEventByDelegate.Run();
            for (int i = 0; i < 11; i++)
            {
                myEventByDelegate.Run();
            }
        }
        void MyShow(string str)
        {
            Console.WriteLine("在事件主函数中触发产生了事件，发生次数：" + ClickNum);
            Console.WriteLine(str);
            ClickNum++;
            if (ClickNum >= 2)
            {
                Console.WriteLine("点击次数够多，取消事件处理");
                myEventByDelegate.ShowEvent -= new MyEventByDelegate.Show(MyShow);
            }
        }
    }
    public class MyEventByDelegate
    {
        public delegate void Show(string str);
        public Show ShowEvent;
        public void Run()
        {
            Console.WriteLine("MyEventByDelegate.Run");
            // 事件-=后会把指针设为0，这里如果不加判断，则会运行空指针，会报错
            if (ShowEvent != null)
                ShowEvent("Run中触发的ShowEvent，delegate名");
        }
    }
}
